package tushare

import (
	"bytes"
	"encoding/json"

	"io/ioutil"
	"net/http"
	"tushare/conf"
	"tushare/model"
	"tushare/model/tushare"
)

type requestRawWeekly struct {
	ApiName string              `json:"api_name"`
	Token   string              `json:"token"`
	Fields  string              `json:"fields"`
	Params  requestParamsWeekly `json:"params"`
}

type requestParamsWeekly struct {
	TsCode    string `json:"ts_code"`
	TradeDate string `json:"trade_date"`
}

type resposeJsonWeekly struct {
	RequestId string           `json:"request_id"`
	Code      int              `json:"code"`
	Data      resposeDataDaily `json:"data"`
}

type resposeDataWeekly struct {
	Items [][]interface{} `json:"items"`
}

func Weekly() {
	stocks := model.StockList()
	for _, v := range stocks {
		pullWeekly(v.TsCode, "")
	}
}

func pullWeekly(tsCode, trade_date string) {
	rw := requestRawWeekly{}
	rw.ApiName = "weekly"
	rw.Token = conf.GetToken()
	rw.Fields = "ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount"
	rw.Params.TradeDate = trade_date
	rw.Params.TsCode = tsCode

	bytesData, _ := json.Marshal(rw)

	resp, _ := http.Post("http://api.waditu.com", "application/json", bytes.NewReader(bytesData))
	body, _ := ioutil.ReadAll(resp.Body)

	jsonStrByte := []byte(body)
	decodeData := resposeJsonDaily{}
	json.Unmarshal(jsonStrByte, &decodeData)

	for _, v := range decodeData.Data.Items {
		d := tushare.Weekly{}
		d.TsCode = v[0].(string)
		d.TradeDate = v[1].(string)
		d.Open = interfaceNilToZero(v[2])
		d.High = interfaceNilToZero(v[3])
		d.Low = interfaceNilToZero(v[4])
		d.Close = interfaceNilToZero(v[5])
		d.PreClose = interfaceNilToZero(v[6])
		d.Change = interfaceNilToZero(v[7])
		d.PctChg = interfaceNilToZero(v[8])
		d.Vol = interfaceNilToZero(v[9])
		d.Amount = interfaceNilToZero(v[10])

		tushare.WeeklyCreate(d)
	}

}
